package com.ruoyi.web.controller.pack;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pack.domain.PackWarehouse;
import com.ruoyi.pack.domain.PackContainer;
import com.ruoyi.pack.domain.dto.PackWarehouseSummaryDto;
import com.ruoyi.pack.service.IPackWarehouseService;

/**
 * 仓库Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/pack/warehouse")
public class PackWarehouseController extends BaseController
{
    @Autowired
    private IPackWarehouseService packWarehouseService;

    /**
     * 查询仓库列表
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:list')")
    @GetMapping("/list")
    public TableDataInfo list(PackWarehouse packWarehouse)
    {
        startPage();
        List<PackWarehouse> list = packWarehouseService.selectPackWarehouseList(packWarehouse);
        return getDataTable(list);
    }

    /**
     * 导出仓库列表
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:export')")
    @Log(title = "仓库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PackWarehouse packWarehouse)
    {
        List<PackWarehouse> list = packWarehouseService.selectPackWarehouseListForExport(packWarehouse);
        ExcelUtil<PackWarehouse> util = new ExcelUtil<PackWarehouse>(PackWarehouse.class);
        util.exportExcel(response, list, "仓库数据");
    }

    /**
     * 获取仓库详细信息
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:query')")
    @GetMapping(value = "/{warehouseId}")
    public AjaxResult getInfo(@PathVariable("warehouseId") Long warehouseId)
    {
        return success(packWarehouseService.selectPackWarehouseByWarehouseId(warehouseId));
    }

    /**
     * 新增仓库
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:add')")
    @Log(title = "仓库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PackWarehouse packWarehouse)
    {
        if (UserConstants.NOT_UNIQUE == packWarehouseService.checkWarehouseCodeUnique(packWarehouse))
        {
            return error("新增仓库'" + packWarehouse.getWarehouseName() + "'失败，仓库编码已存在");
        }
        packWarehouse.setCreateBy(getUsername());
        
        // 如果包含围栏信息，使用带围栏的新增方法
        if (packWarehouse.getFenceList() != null && !packWarehouse.getFenceList().isEmpty())
        {
            Map<String, Object> result = packWarehouseService.insertPackWarehouseWithFence(packWarehouse);
            return success(result);
        }
        else
        {
            return toAjax(packWarehouseService.insertPackWarehouse(packWarehouse));
        }
    }

    /**
     * 修改仓库
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:edit')")
    @Log(title = "仓库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody PackWarehouse packWarehouse)
    {
        if (UserConstants.NOT_UNIQUE == packWarehouseService.checkWarehouseCodeUnique(packWarehouse))
        {
            return error("修改仓库'" + packWarehouse.getWarehouseName() + "'失败，仓库编码已存在");
        }
        packWarehouse.setUpdateBy(getUsername());
        
        // 如果包含围栏操作，使用带围栏的修改方法
        if (packWarehouse.getFenceOperations() != null && !packWarehouse.getFenceOperations().isEmpty())
        {
            Map<String, Object> result = packWarehouseService.updatePackWarehouseWithFence(packWarehouse);
            return success(result);
        }
        else
        {
            return toAjax(packWarehouseService.updatePackWarehouse(packWarehouse));
        }
    }

    /**
     * 删除仓库
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:remove')")
    @Log(title = "仓库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{warehouseIds}")
    public AjaxResult remove(@PathVariable Long[] warehouseIds, @RequestParam(defaultValue = "false") boolean force)
    {
        // 如果只删除一个仓库且需要返回详细信息，使用新的删除方法
        if (warehouseIds.length == 1)
        {
            Map<String, Object> result = packWarehouseService.deletePackWarehouseWithFence(warehouseIds[0], force);
            return success(result);
        }
        else
        {
            // 批量删除仍使用原方法
            return toAjax(packWarehouseService.deletePackWarehouseByWarehouseIds(warehouseIds));
        }
    }

    /**
     * 获取仓库选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        List<PackWarehouse> warehouses = packWarehouseService.selectPackWarehouseList(new PackWarehouse());
        return success(warehouses);
    }

    // 导入功能已移除，如需使用请取消注释
    /*
    @PreAuthorize("@ss.hasPermi('pack:warehouse:import')")
    @Log(title = "仓库", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PackWarehouse> util = new ExcelUtil<PackWarehouse>(PackWarehouse.class);
        List<PackWarehouse> warehouseList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = packWarehouseService.importWarehouse(warehouseList, updateSupport, operName);
        return success(message);
    }

    @PreAuthorize("@ss.hasPermi('pack:warehouse:import')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil<PackWarehouse> util = new ExcelUtil<PackWarehouse>(PackWarehouse.class);
        util.importTemplateExcel(response, "仓库数据");
    }
    */

    /**
     * 库房汇总统计查询
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:summary')")
    @GetMapping("/summary")
    public TableDataInfo warehouseSummary(PackContainer packContainer)
    {
        startPage();
        // 设置公司权限过滤 - 只查询当前用户所属公司的器具
        // 注意：这里需要根据实际的用户-公司关联关系来设置companyId
        // packContainer.setCompanyId(getCurrentUserCompanyId());

        List<PackWarehouseSummaryDto> list = packWarehouseService.selectWarehouseSummary(packContainer);
        return getDataTable(list);
    }

    /**
     * 获取库房汇总详情列表
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:summary')")
    @GetMapping("/summary/detail")
    public TableDataInfo warehouseSummaryDetail(PackContainer packContainer)
    {
        startPage();
        // 设置公司权限过滤 - 只查询当前用户所属公司的器具
        // packContainer.setCompanyId(getCurrentUserCompanyId());

        List<PackContainer> list = packWarehouseService.selectWarehouseSummaryDetail(packContainer);
        return getDataTable(list);
    }

    /**
     * 导出库房汇总统计数据
     */
    @PreAuthorize("@ss.hasPermi('pack:warehouse:summary')")
    @Log(title = "库房汇总统计", businessType = BusinessType.EXPORT)
    @PostMapping("/summary/export")
    public void exportWarehouseSummary(HttpServletResponse response, PackContainer packContainer)
    {
        List<PackWarehouseSummaryDto> list = packWarehouseService.selectWarehouseSummary(packContainer);
        ExcelUtil<PackWarehouseSummaryDto> util = new ExcelUtil<PackWarehouseSummaryDto>(PackWarehouseSummaryDto.class);
        util.exportExcel(response, list, "库房汇总统计数据");
    }
}